<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班主任" prop="headTeacher">
        <el-input
          v-model="queryParams.headTeacher"
          placeholder="请输入班主任"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['classes:classes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['classes:classes:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['classes:classes:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['classes:classes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班级ID" align="center" prop="classId" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="年级" align="center" prop="grade" />
      <el-table-column label="班主任" align="center" prop="headTeacher" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['classes:classes:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['classes:classes:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="classesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入年级" />
        </el-form-item>
        <el-form-item label="班主任" prop="headTeacher">
          <el-input v-model="form.headTeacher" placeholder="请输入班主任" />
        </el-form-item>
        <el-divider content-position="center">学生管理信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddStudents">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteStudents">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="studentsList" :row-class-name="rowStudentsIndex" @selection-change="handleStudentsSelectionChange" ref="students">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="学生姓名" prop="studentName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.studentName" placeholder="请输入学生姓名" />
            </template>
          </el-table-column>
          <el-table-column label="出生日期" prop="birthDate" width="240">
            <template #default="scope">
              <el-date-picker clearable
                v-model="scope.row.birthDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择出生日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="联系电话" prop="phone" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.phone" placeholder="请输入联系电话" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Classes">
import { listClasses, getClasses, delClasses, addClasses, updateClasses } from "@/api/classes/classes"

const { proxy } = getCurrentInstance()

const classesList = ref([])
const studentsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedStudents = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    className: null,
    headTeacher: null
  },
  rules: {
    className: [
      { required: true, message: "班级名称不能为空", trigger: "blur" }
    ],
    grade: [
      { required: true, message: "年级不能为空", trigger: "blur" }
    ],
    headTeacher: [
      { required: true, message: "班主任不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询班级管理列表 */
function getList() {
  loading.value = true
  listClasses(queryParams.value).then(response => {
    classesList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    classId: null,
    className: null,
    grade: null,
    headTeacher: null
  }
  studentsList.value = []
  proxy.resetForm("classesRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.classId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加班级管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _classId = row.classId || ids.value
  getClasses(_classId).then(response => {
    form.value = response.data
    studentsList.value = response.data.studentsList
    open.value = true
    title.value = "修改班级管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["classesRef"].validate(valid => {
    if (valid) {
      form.value.studentsList = studentsList.value
      if (form.value.classId != null) {
        updateClasses(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addClasses(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _classIds = row.classId || ids.value
  proxy.$modal.confirm('是否确认删除班级管理编号为"' + _classIds + '"的数据项？').then(function() {
    return delClasses(_classIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 学生管理序号 */
function rowStudentsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 学生管理添加按钮操作 */
function handleAddStudents() {
  let obj = {}
  obj.studentName = ""
  obj.gender = ""
  obj.birthDate = ""
  obj.phone = ""
  studentsList.value.push(obj)
}

/** 学生管理删除按钮操作 */
function handleDeleteStudents() {
  if (checkedStudents.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的学生管理数据")
  } else {
    const studentss = studentsList.value
    const checkedStudentss = checkedStudents.value
    studentsList.value = studentss.filter(function(item) {
      return checkedStudentss.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleStudentsSelectionChange(selection) {
  checkedStudents.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('classes/classes/export', {
    ...queryParams.value
  }, `classes_${new Date().getTime()}.xlsx`)
}

getList()
</script>
